require 'net/pop'
require 'mms2r'
require 'mms2r/media'
require 'fileutils'

class Notifier < ActionMailer::Base
  def feedback(from_user, feedback_text)
    recipients %w(kmamyk@gmail.com mamykina@gmail.com)
    from       'support@moddweb.com'
    subject    "[MAHI] Feedback from #{from_user.login}"
    body       :from_user => from_user, :feedback_text => feedback_text
  end
  
  def receive(email)
    logger.info "Received email:"
    logger.info email
    mms = MMS2R::Media.create(email)
    # process finds all the media in a MMS, strips advertsing, then
    # writes the user generated media to disk in a temporary subdirectory
    mms.process
    puts "MMS has default carrier subject!" unless mms.get_subject
    # access the senders phone number
    puts "MMS was from phone #{mms.get_number}"
    # most MMS are either image or video, get_media will return the largest
    # (non-advertising) video or image found
    file = mms.get_media
    puts "MMS had a media: #{file.inspect}" unless file.nil?
    # get_text return the largest (non-advertising) text found
    file = mms.get_text
    puts "MMS had some text: #{file.inspect}" unless file.nil?
    # mms.media is a hash that is indexed by mime-type.
    # The mime-type key returns an array of filepaths
    # to media that were extract from the MMS and
    # are of that type
    mms.media['image/jpeg'].each {|f| puts "#{f}"}
    mms.media['text/plain'].each {|f| puts "#{f}"}
  
    # print the text (assumes MMS had text)
    text = IO.readlines(mms.media['text/plain'][0]).join
    puts text
  
    # save the image (assumes MMS had a jpeg)
    FileUtils.cp mms.media['image/jpeg'][0], "#{RAILS_ROOT}/public/attachments", :verbose => true
  
    puts "does the MMS have video? #{!mms.media['video/quicktime'].nil?}"
  
    #remove all the media that was put to temporary disk
    mms.purge
  
    # Block support, process and receive all media types of video.
    # Purge is called at the conclusion of the block so be sure
    # to do something with the bits you are looking for
    #mms.process do |media_type, files|
      # assumes a Clip model
      #Clip.create(:uploaded_data => files.first, :title => "From phone") if media_type =~ /video/
    #end
  end
  
  def self.receive_pop_emails
    logger.info "Running Mail Importer..." 
    Net::POP3.start(ActionMailer::Base.smtp_settings[:address], nil, ActionMailer::Base.smtp_settings[:user_name], ActionMailer::Base.smtp_settings[:password]) do |pop|
      if pop.mails.empty?
        logger.info "NO MAIL" 
      else
        pop.mails.each do |email|
          begin
            logger.info "receiving mail..." 
            Notifier.receive(email.pop)
            email.delete
          rescue Exception => e
            logger.error "Error receiving email at " + Time.now.to_s + "::: " + e.message
          end
        end
      end
    end
    logger.info "Finished Mail Importer." 
  end
end
